/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ifconnect.view.managedBean;

import ifconnect.model.dao.CampusDao;
import ifconnect.model.entity.Campus;
import ifconnect.model.entity.Curso;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.imageio.stream.FileImageOutputStream;
import javax.servlet.ServletContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.map.PointSelectEvent;
import org.primefaces.model.UploadedFile;
import org.primefaces.model.map.DefaultMapModel;
import org.primefaces.model.map.LatLng;
import org.primefaces.model.map.MapModel;

/**
 *
 * @author Genemes
 */
@ManagedBean(name = "campusMB")
@ViewScoped
public class CampusMB implements Serializable {

    CampusDao campusDao;
    private Campus campus;
    private String uf;
    private String[] estados = {"Acre", "Alagoas", "Amapá", "Amazonas", "Bahia", "Ceará", "Distrito Federal", "Espírito Santo", "Goiás", "Maranhão",
        "Mato Grosso", "Mato Grosso do Sul", "Minas Gerais", "Pará", "Paraíba", "Paraná", "Pernambuco", "Piauí", "Rio de Janeiro", "Rio Grande do Norte",
        "Rio Grande do Sul", "Rondônia", "Roraima", "Santa Catarian", "São Paulo", "Sergipe", "Tocantins"};
    private UploadedFile file;
    private Curso curso;
    private List<Campus> listaCampus;
    private Campus campusSelecionado;
    private MapModel emptyModel;

    public CampusMB() {
        this.campusDao = new CampusDao();
        this.campus = new Campus();
        this.curso = new Curso();
        emptyModel = new DefaultMapModel();
        try {
            this.listarCampus();
        } catch (Exception ex) {
            Logger.getLogger(CampusMB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public Campus getCampus() {
        return campus;
    }

    public void setCampus(Campus campus) {
        this.campus = campus;
    }

    public String getUf() {
        return uf;
    }

    public void setUf(String uf) {
        this.uf = uf;
    }

    public String[] getEstados() {
        return estados;
    }

    public void setEstados(String[] estados) {
        this.estados = estados;
    }

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

    public Curso getCurso() {
        return curso;
    }

    public void setCurso(Curso curso) {
        this.curso = curso;
    }

    public List<Campus> getListaCampus() {
        return listaCampus;
    }

    public void setListaCampus(List<Campus> listaCampus) {
        this.listaCampus = listaCampus;
    }

    public Campus getCampusSelecionado() {
        return campusSelecionado;
    }

    public void setCampusSelecionado(Campus campusSelecionado) {
        this.campusSelecionado = campusSelecionado;
    }

    public MapModel getEmptyModel() {
        return emptyModel;
    }

    public void setEmptyModel(MapModel emptyModel) {
        this.emptyModel = emptyModel;
    }

    public void fileUploadAction(FileUploadEvent event) {

        if (this.campus.getFoto() == null) {
            Calendar c = new GregorianCalendar();
            String[] partesNome = event.getFile().getFileName().split("\\.");

            String nomeArq = "campus" + c.get(Calendar.DAY_OF_MONTH) + c.get(Calendar.MONTH) + c.get(Calendar.YEAR) + "_" + c.get(Calendar.HOUR) + c.get(Calendar.MINUTE) + c.get(Calendar.SECOND) + "." + partesNome[1];

            ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
            String newFileName = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "campus" + File.separator + nomeArq;

            FileImageOutputStream imageOutput;
            try {

                this.campus.setFoto(nomeArq);


                imageOutput = new FileImageOutputStream(new File(newFileName));
                imageOutput.write(event.getFile().getContents(), 0, event.getFile().getContents().length);
                imageOutput.close();


            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
            String caminhoAtualizando = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "campus" + File.separator + this.campus.getFoto();
            
            FileImageOutputStream imageOutput;
            try {


                imageOutput = new FileImageOutputStream(new File(caminhoAtualizando));
                imageOutput.write(event.getFile().getContents(), 0, event.getFile().getContents().length);
                imageOutput.close();


            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public String reiniciar() {
        this.curso = new Curso();
        return null;
    }

    public void addCampus() throws Exception {
        this.campus.setUf(uf);

        String msg = this.campusDao.salvar(this.campus);

        FacesMessage message = new FacesMessage(msg);
        message.setSeverity(FacesMessage.SEVERITY_INFO);
        FacesContext.getCurrentInstance().addMessage(null, message);

        this.uf = null;
        this.campus = new Campus();
        this.listaCampus = null;
        this.listarCampus();
    }

    public void listarCampus() throws Exception {
        if (this.listaCampus == null) {
            this.listaCampus = this.campusDao.listarTodos(Campus.class);
        }
    }

    public void excluirCampus() throws Exception {

        if (this.campusSelecionado != null) {

            ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
            String url = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "campus" + File.separator + campusSelecionado.getFoto();

            File f = new java.io.File(url);
            f.delete();

            String msg = this.campusDao.remover(this.campusSelecionado);

            FacesMessage message = new FacesMessage(msg);
            message.setSeverity(FacesMessage.SEVERITY_INFO);
            FacesContext.getCurrentInstance().addMessage(null, message);

            this.listaCampus = null;
            this.listarCampus();
        }
    }

    public void atualizaCampus() {
        if (this.campusSelecionado != null) {
            this.campus = this.campusSelecionado;
            this.uf = campusSelecionado.getUf();
        }
    }

    public void onPointSelect(PointSelectEvent event) {
        LatLng latlng = event.getLatLng();
        this.campus.setLatitude(latlng.getLat());
        this.campus.setLongitude(latlng.getLng());
    }
//    public void upload() {
//        try {
//            if (this.file == null) {
//                System.out.println("NULOOOOOOOOOOOOOOOOOOOOOOOOO");
//            }
//            FacesContext aFacesContext = FacesContext.getCurrentInstance();
//            ServletContext context = (ServletContext) aFacesContext.getExternalContext().getContext();
//
//            InputStream in = new BufferedInputStream(file.getInputstream());
//
//            String realPath = context.getRealPath(File.separator);
//            String caminho = realPath + File.separator + "images" + File.separator + "campus" + File.separator + file.getFileName();
//            File arq = new File(caminho);
//
//            this.campus.setFoto(caminho);
//            FileOutputStream fout = new FileOutputStream(arq);
//
//            while (in.available() != 0) {
//
//                fout.write(in.read());
//
//            }
//
//            fout.close();
//
//        } catch (Exception ex) {
//
//            ex.printStackTrace();
//
//        }
//    }
}
